<template>
  <li>
    <label>
      <input
        type="checkbox"
        :checked="todo.status"
        @change="changeTodo(todo.id)"
      />
      <span v-show="!todo.isEdit">{{ todo.title }}</span>
      <input
        ref="inputTitle"
        v-show="todo.isEdit"
        type="text"
        :value="todo.title"
        @blur="updateTodo(todo, $event)"
      />
    </label>
    <button class="btn btn-danger" @click="deleteById(todo.id)">删除</button>
    <button v-show="!todo.isEdit" class="btn btn-edit" @click="editTodo(todo)">
      编辑
    </button>
  </li>
</template>

<script>
import pubsub from 'pubsub-js';
export default {
  name: 'MyItem',
  props: ['todo'],
  methods: {
    changeTodo(id) {
      this.$bus.$emit('changeStatus', id);
    },
    deleteById(id) {
      if (confirm('确定删除吗?')) {
        //全局事件总线写法
        // this.$bus.$emit('deleteTodo', id);
        pubsub.publish('deleteTodo', id); //消息订阅与发布写法
      }
    },
    editTodo(todo) {
      //如果有isEdit属性  直接设置为true
      if (todo.hasOwnProperty('isEdit')) {
        todo.isEdit = true;
        //如果没有isEdit属性就追加一个，并且设置为true
      } else this.$set(todo, 'isEdit', true);
      //this.$nextTick(callback)  在下一次dom更新完之后才调用callback函数
      this.$nextTick(() => this.$refs.inputTitle.focus()); //点击编辑之后like获取焦点
    },
    updateTodo(todo, event) {
      // console.log(todo.id, event.target.value);
      if (!event.target.value) return alert('内容不能为空!!');
      todo.isEdit = false;
      this.$bus.$emit('updateTodo', todo.id, event.target.value);
    },
  },
};
</script>

<style scoped>
/*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:hover {
  background-color: #ddd;
}

li:hover button {
  display: block;
}
li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}
</style>
